package logger

import (
	"fmt"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
	"strings"
	"time"
)

var logger *zap.SugaredLogger

func sugar(filename string) {
	syncWriter := zapcore.AddSync(&lumberjack.Logger{
		Filename:  filename,
		MaxSize:   1 << 30, //1G
		LocalTime: true,
		Compress:  true,
	})

	// 自定义时间输出格式
	customTimeEncoder := func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
		enc.AppendString(t.Format("2006-01-02 15:04:05") + "(" + fmt.Sprintf("%d", t.Unix()) + ")")
	}
	// 自定义日志级别显示
	customLevelEncoder := func(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
		enc.AppendString(strings.ToLower(level.CapitalString()))
	}
	// 自定义文件：行号输出项
	customCallerEncoder := func(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
		enc.AppendString("[" + caller.TrimmedPath() + "]")
	}

	encoder := zapcore.EncoderConfig{
		CallerKey:      "caller", // 打印文件名和行数
		LevelKey:       "lv",
		MessageKey:     "msg",
		TimeKey:        "ts",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeTime:     customTimeEncoder,   // 自定义时间格式
		EncodeLevel:    customLevelEncoder,  // 小写编码器
		EncodeCaller:   customCallerEncoder, // 全路径编码器
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeName:     zapcore.FullNameEncoder,
	}
	core := zapcore.NewCore(zapcore.NewJSONEncoder(encoder), syncWriter, zap.NewAtomicLevelAt(zapcore.DebugLevel))

	var zapLogger *zap.Logger
	if filename == "" {
		coreConsole := zapcore.NewCore(zapcore.NewConsoleEncoder(encoder), zapcore.Lock(os.Stdout), zap.NewAtomicLevelAt(zapcore.DebugLevel))
		zapLogger = zap.New(zapcore.NewTee(core, coreConsole), zap.AddCaller(), zap.AddCallerSkip(1))
	} else {
		zapLogger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
	}

	logger = zapLogger.Sugar()
}

func New(filename string) {
	sugar(filename)
}

func Close() {
	logger.Sync()
}
